import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import lodashSet from 'lodash.set';

import { RootState } from '@/store';

interface InitialState {
  templateConfig?: any;
  price?: string;
  schemaCode?: string;
  agreeRecord: boolean;
  value: number;
  list: any[];
  coverages: { [key: string]: string };
  loading: { [key: string]: any };
  formValues: { [key: string]: any };
  informAgreeInfo: boolean[];
  validateCount: number;
}

const initialState: InitialState = {
  agreeRecord: false,
  validateCount: 0,
  value: 0,
  list: [],
  coverages: {},
  formValues: {},
  informAgreeInfo: [],
  loading: {
    template: {
      valuation: false,
    },
  },
};

export const effect = {
  init: {},
};

export const initSlice = createSlice({
  name: 'init',
  initialState,
  reducers: {
    increment: state => {
      state.value += 1;
    },
    decrement: state => {
      state.value -= 1;
    },
    // Use the PayloadAction type to declare the contents of `action.payload`
    incrementByAmount: (state, action: PayloadAction<number>) => {
      state.value += action.payload;
    },
    setAgreeRecord: (state, action: PayloadAction<boolean>) => {
      state.agreeRecord = action.payload;
    },
    setValidateCount: (state, action: PayloadAction<number>) => {
      state.validateCount = action.payload;
    },
    setFormValues: (state, action: PayloadAction<{ [key: string]: any }>) => {
      state.formValues = action.payload;
    },
    setPrice: (state, action: PayloadAction<string>) => {
      state.price = action.payload;
    },
    setSchemaCode: (state, action: PayloadAction<string>) => {
      state.schemaCode = action.payload;
    },
    setInformAgreeInfo: (state, action: PayloadAction<boolean[]>) => {
      state.informAgreeInfo = action.payload;
    },
  },
  extraReducers: builder => {
    builder.addMatcher(
      action =>
        ['/pending', '/fulfilled', '/rejected'].some((item: string) => action.type.endsWith(item)),
      (state, action) => {
        const actionTypeArr: string[] = action.type.split('/');
        actionTypeArr.splice(-1);

        const actionPath = actionTypeArr.reduce((prev: string, curr: string) => `${prev}.${curr}`);
        const loadingStatus = action.type.endsWith('/pending');

        lodashSet(state.loading, actionPath, loadingStatus);
      },
    );
  },
});

// Action creators are generated for each case reducer function
export const {
  increment,
  decrement,
  incrementByAmount,
  setAgreeRecord,
  setValidateCount,
  setFormValues,
  setPrice,
  setSchemaCode,
  setInformAgreeInfo,
} = initSlice.actions;

export const selectCount = (state: RootState) => state.init.value;

export default initSlice.reducer;